#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Reflection;

using octalforty.Componento.ComponentModel.Installation.FileSystem;
using octalforty.Wizardby.Core.Db;
using octalforty.Wizardby.Core.Migration;
using octalforty.Wizardby.Core.Migration.Impl;
using octalforty.Wizardby.Db.SQLite;

namespace octalforty.Componento.ComponentModel.Impl
{
    public abstract class SQLiteServiceBase : IPartImportsSatisfiedNotification
    {
        #region Private Fields
        private IDbPlatform dbPlatform;
        private string connectionString;
        private string databaseRootDirectory;
        private IFileSystemManagerService fileSystemManager;
        #endregion
        
        #region Public Properties
        public virtual string DatabaseRootDirectory
        {
            [DebuggerStepThrough]
            get { return databaseRootDirectory; }
            [DebuggerStepThrough]
            set { databaseRootDirectory = value; }
        }
        #endregion

        #region Protected Properties
        protected IDbPlatform DbPlatform
        {
            [DebuggerStepThrough]
            get { return dbPlatform; }
            [DebuggerStepThrough]
            set { dbPlatform = value; }
        }

        protected string ConnectionString
        {
            [DebuggerStepThrough]
            get { return connectionString; }
            [DebuggerStepThrough]
            set { connectionString = value; }
        }

        [Import()]
        public IFileSystemManagerService FileSystemManager
        {
            [DebuggerStepThrough]
            get { return fileSystemManager; }
            [DebuggerStepThrough]
            set { fileSystemManager = value; }
        }
        #endregion

        protected SQLiteServiceBase()
        {
            DatabaseRootDirectory = Directory.GetCurrentDirectory();
        }

        #region IPartImportsSatisfiedNotification Members
        public void OnImportsSatisfied()
        {
            DbPlatform = new SQLitePlatform();

            string databasePath = Path.Combine(DatabaseRootDirectory, DatabaseFileName);
            IDbConnectionStringBuilder connectionStringBuilder =
                DbPlatform.CreateConnectionStringBuilder();
            connectionStringBuilder.AppendKeyValuePair("database", databasePath);

            ConnectionString = connectionStringBuilder.ToString();

            if(FileSystemManager.DirectoryExists(DatabaseRootDirectory))
                FileSystemManager.CreateDirectory(DatabaseRootDirectory);

            if(!FileSystemManager.FileExists(databasePath))
                DbPlatform.DeploymentManager.Deploy(ConnectionString, DbDeploymentMode.Deploy);

            DbCommandExecutionStrategy dbCommandExecutionStrategy = new DbCommandExecutionStrategy();

            IMigrationService migrationService =
                new MigrationService(DbPlatform,
                    new DbMigrationVersionInfoManager(DbPlatform, dbCommandExecutionStrategy, "SchemaInfo"),
                    new DbMigrationScriptExecutive(dbCommandExecutionStrategy), null);

            using(Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(DatabaseMigrationDefinitionResourceName))
                migrationService.Migrate(ConnectionString, null, new StreamReader(stream));
        }
        #endregion

        #region Overridables
        protected abstract string DatabaseFileName
        { get; }

        protected abstract string DatabaseMigrationDefinitionResourceName
        { get; }
        
        #endregion

    }
}
